angular.module('driver')

.directive('ngThumb', ['$window', function($window) {
  var helper = {
    support: !!($window.FileReader && $window.CanvasRenderingContext2D),
    isFile: function(item) {
      return angular.isObject(item) && item instanceof $window.File;
    },
    isImage: function(file) {
      var type = '|' + file.type.slice(file.type.lastIndexOf('/') + 1) + '|';
      return '|jpg|png|jpeg|bmp|gif|'.indexOf(type) !== -1;
    }
  };

  return {
    restrict: 'A',
    template: '<img>',
    link: function(scope, element, attributes) {
      console.log(0)
      if (!helper.support) return;

      var params = scope.$eval(attributes.ngThumb);
      console.log(1)
      console.log(params.file);
      //if (!helper.isFile(params.file)) return;
      console.log(2);
      
      
      //if (!helper.isImage(params.file)) return;
      console.log(3)
      var canvas = element.find('img');
      var reader = new FileReader();
      console.log(reader)
      reader.onload = onLoadFile;
      reader.readAsDataURL(params.file);

      function onLoadFile(event) {
        var img = new Image();
        img.onload = onLoadImage;
        img.src = event.target.result;
      }

      function onLoadImage() {
        canvas[0].width = params.width;
        canvas[0].height = params.height;
        canvas[0].src = this.src;
        console.log(this.src);
        return;
        
        var width = params.width || this.width / this.height * params.height;
        var height = params.height || this.height / this.width * params.width;
        canvas.attr({
          width: width,
          height: height
        });
        canvas[0].getContext('2d').drawImage(this, width / 2, height / 2, width, height);
      }
    }
  };
}]);